package cn.javav.sso.dao.impl;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import cn.javav.sso.dao.BaseDao;

public abstract class BasoDaoImpl<T> implements BaseDao<T> {
	 
	Class<T> clazz;
	String entityName; 
	SessionFactory sessionFactory;
	
	@Override
	public void insert(T entity) {
		sessionFactory.getCurrentSession().save(entity);
	}
	
	@Override
	public void delete(T entity) {
		sessionFactory.getCurrentSession().delete(entity);
	}

	@Override
	public void deleteById(int id) {
		if(id > 0){
			String sql = "DELETE FROM " + entityName + "s WHERE " + 
					entityName.toUpperCase() + "_ID = ?";
			Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
			query.setInteger(0, id);
			query.executeUpdate();
		}
	}

	@Override
	public void update(T entity) {
		sessionFactory.getCurrentSession().update(entity);
	}

	@Override
	public T getById(int id) {
		if(id > 0){
			return sessionFactory.getCurrentSession().get(clazz, id);
		}
		return null;
	}

	@Override
	public List<T> getByName(String name) {
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getAll(){
		Query query  = sessionFactory.getCurrentSession().createQuery("FROM " + clazz.getSimpleName());
		List<T> resualt = query.list();
		return resualt;
	}
    @SuppressWarnings("unchecked")
	@Resource
    public void setSessionFactory(SessionFactory HibernatesessionFactory) {
    	this.sessionFactory = HibernatesessionFactory;
        Type genType = this.getClass().getGenericSuperclass();   
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();   
        this.clazz = (Class<T>) params[0];
        entityName = clazz.getSimpleName().toLowerCase();
    }
}
